<template>
  <div class="absolute inset-0">
    <div id="render" class="w-full h-full"></div>
  </div>
</template>

<script setup lang="ts" name="CreativeChuangkit">
import CktDesign from '@chuangkit/chuangkit-design'
import * as CktApi from '@/api/creative/chuangkit'
import { onMounted } from 'vue'
import { getTenantId } from '@/utils/auth'

let cktInstance: any = null

// 获取用户id
const userFlag = getTenantId()
const appId = '1cf71fc825044b6ea6858ce9bbd8b663'
const settingCode = 'W4WR'

/** 监听模板中心参数变化 */
const onParamsChange = (params: {
  format: number
  pageNo: number
  priceType: number
  sortType: number
  categoryId?: number
  kindId?: number
}) => {
  console.log('on params change: ', params)
}

/** 用户点击模板中心的模板后通知 */
const onChooseTemplate = async (templateItem: {
  clickTime: Date
  price: number
  templateId: number
  templateName: string
  templateThumbUrl: string
}) => {
  // 付费调起模板编辑器
  const payConfig = { charge_type: 2 }
  // 调用接口获取packageId
  const packageId = await CktApi.requestPackageId()

  // 如果能获取到付费id，则更改
  if (packageId) {
    payConfig.charge_type = 1
    payConfig['package_id'] = packageId
  }
  // 需要签名
  const needSign = {
    app_id: appId,
    // 用户id
    user_flag: userFlag,
    expire_time: Date.now() + 2 * 60 * 1000,
    device_type: 1,
    template_id: templateItem.templateId,
    setting_code: 'RBGJ',
    ...payConfig,
    charging_template_limit: 2,
    coop_font_limit: 2,
    coop_material_limit: 2
  }

  // 获取sign接口
  const sign = await CktApi.getTemplateEditorSign(needSign)

  const design = new CktDesign({
    ...needSign,
    sign,
    show_name: '1',
    show_watermark: '1'
  })
  design.open()
}

/** 挂载创客贴 */
onMounted(async () => {
  const needSign = {
    appId,
    settingCode,
    timestamp: Date.now() - 1000
  }
  const sign = await CktApi.getTemplateCenterSign(needSign)

  const options = {
    ...needSign,
    sign,
    container: '#render'
  }

  console.log(options)
  cktInstance = CktDesign.createTemplateCenter(options)
  await cktInstance.open()
  cktInstance.onParamsChange(onParamsChange)
  cktInstance.onChooseTemplate(onChooseTemplate)
})

/** 卸载创客贴 */
onBeforeUnmount(() => {
  cktInstance && cktInstance.close()
})
</script>
